package com.itobase.questionnaire.controller;


import com.alibaba.fastjson.JSONObject;
import com.itobase.questionnaire.VO.UserBaseVO;
import com.itobase.questionnaire.dto.MarkDTO;
import com.itobase.questionnaire.model.*;
import com.itobase.questionnaire.model.auth.User;
import com.itobase.questionnaire.repository.SubmitRepository;
import com.itobase.questionnaire.repository.SurveyGroupRepository;
import com.itobase.questionnaire.repository.SurveyRepository;
import com.itobase.questionnaire.repository.UserRepository;
import com.itobase.questionnaire.service.IOutcomeService;
import com.itobase.questionnaire.service.IUserService;
import com.itobase.questionnaire.service.impl.UrlService;
import com.itobase.questionnaire.template.Constant;
import com.itobase.questionnaire.template.Page;
import com.itobase.questionnaire.util.AuthUtil;
import com.itobase.questionnaire.util.ExcelUtil;
import com.itobase.questionnaire.util.MD5Util;
import com.itobase.questionnaire.util.Message;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import static org.springframework.data.mongodb.core.query.Criteria.where;

@RestController
@RequestMapping(value = "user")
public class UserController {


    @Autowired
    IUserService userService;

    @Autowired
    UserRepository userRepository;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    SubmitRepository submitRepository;

    @Autowired
    UrlService urlService;

    @Autowired
    SurveyRepository surveyRepository;

    @Autowired
    SurveyGroupRepository surveyGroupRepository;

    @Autowired
    IOutcomeService outcomeService;

    @Autowired
    SurveyController surveyController;


    @GetMapping("{username}")
    public Message findByUsername(@PathVariable("username") String username) {
        return Message.createSuc(userService.findByUsername(username));
    }


    @GetMapping("type")
    public Message getLoginType() throws Throwable {
        User user = AuthUtil.getUser().orElseThrow(() -> new RuntimeException("请先登录"));
        if(user.getUserTypeId().equals(Constant.TEACID)){
            return Message.createSuc(0);//0代表教师
        }else if(user.getUserTypeId().equals(Constant.STUID) || user.getUserTypeId().equals(Constant.GRADUATE_STUDENT_ID)){
            return Message.createSuc(1);//1代表学生
        }else if(user.getUserTypeId().equals(Constant.ADMINID)){
            return Message.createSuc(0);
        } else if(user.getUsername().equals("anonymous")){
            return Message.createErr("匿名登录");
        }else {
            return Message.createSuc("当前身份未知");
        }
    }

    @GetMapping("id")
    public Message getUserId() throws Throwable {
        return Message.createSuc(AuthUtil.getUserId());
    }

    @PostMapping
    public Message addUser(@Validated @RequestBody User user) {
        return Message.createSuc(userService.insert(user));
    }

    /**
     * 修改密码
     * @return
     */
    @PutMapping
    public Message changePwd(@RequestParam String old, @RequestParam String newPwd) throws Throwable {
        String username = AuthUtil.getUsername();
        User user = userRepository.findByUsername(username);
        if (user.getPassword().equals(MD5Util.encode(old))) {
            user.setPassword(MD5Util.encode(newPwd));
        } else {
            return Message.createErr("请输入正确的旧密码");
        }
        return Message.createSuc(userRepository.save(user));
    }

    /**
     * 通过excel导入人员
     * @param file excel
     * @param userTypeId 导入人员type
     * @return
     */
    @PostMapping(path = "addUsers")
    public Message addStudentByExcel(@RequestParam MultipartFile file,
                                     @RequestParam String userTypeId)
    {
        int resultCount = userService.addUsersByExcel(file,userTypeId);
        return Message.createSuc(resultCount);
    }



    @PostMapping(path = "select")
    public Message selectUser(@RequestParam(required = true)String tagId,
                              @RequestParam(required = true)Integer number,
                              @RequestParam(required = false)List<User> userList)
    {
        //todo 第一版不做筛选
        return null;

    }

    @GetMapping(path = "")
    public Message getPerson(@PageableDefault(size = 25, page = 0)Pageable pageable,
                             @RequestParam(required = false) String userTypeId,
                             @RequestParam(required = false) String keyWord)
    {

        Pageable pageable_1 = new PageRequest(pageable.getPageNumber()-1,pageable.getPageSize());
        Page<UserBaseVO> userPage = userService.getUser(pageable_1,userTypeId,keyWord);
        return Message.createSuc(userPage);
    }

    /**
     * 禁用用户
     * @param userId
     * @return
     */
    @PutMapping(path = "offUser")
    public Message offUser(@RequestParam String userId)
    {
        userService.offUser(userId);
        return Message.createSuc("禁用用户成功");
    }

    @PutMapping("mark")
    public Message addTag(@RequestBody MarkDTO markDTO)
    {
        return Message.createSuc("");
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @DeleteMapping("{userId}")
    public Message deleteUser(@PathVariable String userId) {
        userService.deleteUser(userId);
        return Message.createSuc("删除成功");
    }

    @GetMapping("testPath")
    public Message getUserPageable() throws Throwable {
        /*List<Survey> surveyList = new ArrayList<>();
        List<SurveyGroup> surveyGroups = new ArrayList<>();
        String[] needChange = new String[]{"创业学院"};
        for (int i = 0; i < needChange.length; i++) {
            Survey survey = surveyRepository.findBySection(needChange[i]);
            SurveyGroup surveyGroup = surveyGroupRepository.findByGroupName(needChange[i]);
            survey.setUserList(Collections.emptyList());
            survey.setSurveyGroupId("");
            surveyRepository.save(survey);
            System.out.println(survey.getId()+"    "+surveyGroup.getId());
            surveyController.setUserList(survey.getId(),surveyGroup.getId());
            System.out.println(survey.getTitle()+"修改成功");
        }
*/
        /*List<Survey> surveyList = surveyRepository.findAll();
        JSONObject jsonObject = new JSONObject();
        for (Survey survey : surveyList) {
            List<Submission> submissionList = submitRepository.findBySurveyId(survey.getId());
            //计算老师总得分
            double teacherGrade = 0d;
            int teacherNum = 0,stuNum = 0;
            double stuGrade = 0d;
            for (Submission submission : submissionList) {
                if(submission.getIdentity().equals(Constant.teacIdentity)){
                    Map<String, String> outcome;
                    outcome = submission.getOutcome();
                    for (Map.Entry<String, String> entry : outcome.entrySet()) {
                        String v = entry.getValue();
                        teacherGrade += Double.valueOf(v);
                        teacherNum++;
                    }
                }else if(submission.getIdentity().equals(Constant.stuIdentity)){
                    Map<String, String> outcome;
                    outcome = submission.getOutcome();
                    Map<Integer,String> answers = submission.getAnswer();
                    String ifValid = answers.get(4);
                    if(ifValid!=null&&ifValid.equals("A.熟悉")){
                        System.out.println(ifValid);
                        for (Map.Entry<String, String> entry : outcome.entrySet()) {
                            String v = entry.getValue();
                            stuGrade += Double.valueOf(v);
                            stuNum++;
                        }
                    }

                }
            }
            JSONObject grade = new JSONObject();
            grade.put("部门名称",survey.getTitle());
            grade.put("教师有效答卷数量",teacherNum);
            grade.put("教师总分",teacherGrade);
            grade.put("学生有效答卷数量",stuNum);
            grade.put("学生总分",stuGrade);
            jsonObject.put(survey.getSection(),grade);
        }*/

        Survey survey = surveyRepository.findBySection("网络中心");
        List<Submission> submissionList = submitRepository.findBySurveyId(survey.getId());
        double total = 0;
        int num = 0;
        for (Submission submission : submissionList) {
            if(submission.getIdentity().equals(Constant.teacIdentity)){
                Map<String, String> outcome;
                outcome = submission.getOutcome();
                for (Map.Entry<String, String> entry : outcome.entrySet()) {
                    String v = entry.getValue();
                    total += Double.valueOf(v);
                    num++;
                }
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total",total);
        jsonObject.put("num",num);
        System.out.println(total/num);

       return Message.createSuc(jsonObject);
    }

    @GetMapping("check")
    public Message check(){
        userService.check();
        return Message.createSuc("无重复信息");
    }

    @GetMapping("range")
    public Message range(@RequestParam Integer number,
                         @RequestParam String userTypeId){
        return Message.createSuc(userService.getRangeUser(number,userTypeId));
    }

    @GetMapping("range2")
    public Message range2(@RequestParam Integer number,
                         @RequestParam String userTypeId){
        return Message.createSuc(userService.getRangeId(number,userTypeId));
    }

}
